import Vue from 'vue'
import VueRouter from 'vue-router'
import HeaderLayout from "@/views/common/HeaderLayout"
import routerJson from "./router.json";


Vue.use(VueRouter)

const RouteView = {
    name: 'RouteView',
    render: h => h('router-view')
};

let hasLoad = false

// 处理动态引入组件函数
const getComponent = (data) => {
    if (!data) return
    // console.log('data--',data)
    data.forEach((item) => {
        item.meta = {
            title: item.title,
        }
        const com = item.component
        if (com) {
            switch (com) {
                case 'HeaderLayout':
                    item.component = HeaderLayout
                    break
                case 'RouteView':
                    item.component = RouteView
                    break
                default: {
                    item.component = () => import('@/views/' + com + '.vue')
                }
            }
            item.redirect =item.redirect?item.redirect: item.children && item.children.length ? item.children[0].path : null
            // 利用递归，处理多级路由
            if (item.children && item.children.length) {
                item.children=item.children.filter(f=>f.type!='button')
                getComponent(item.children)
            }
        }
    })
    return data
}

// 处理动态引入组件函数
const getRouter = (data) => {
    data.forEach((item) => {
        let currenRoutes = router.options.routes;
        let has = currenRoutes.some((it) => it.path == item.path);
        if (!has) {
            router.addRoute({
                path: `${item.path}`,
                name: item.name,
                meta: {
                    title: item.title
                },
                // redirect:item.redirect?item.redirect:null,
                redirect: item.children && item.children.length ? item.children[0].path : null,
                component: item.component,
                children: item.children ? item.children : [],
            });
        }
    })
    hasLoad = true
}

// if(!routerData)
const routes = getComponent(JSON.parse(JSON.stringify(routerJson)))

const router = new VueRouter({
    routes
})
router.beforeEach(async (to, from, next) => {
    // storage.clear()
    // 一天同步一次菜单
    /*if((storage.get("time")&&new Date().getTime()-storage.get("time")>=86400000)||!storage.get("time")){
        storage.clear()
    }*/
    next()
})

// 获取原型对象push函数
const originalPush = VueRouter.prototype.push

// 获取原型对象replace函数
const originalReplace = VueRouter.prototype.replace

// 修改原型对象中的push函数
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

// 修改原型对象中的replace函数
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}
export default router
